package com.sword.demo.concurrent.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步配置
 * @author sword
 * @date 2022/3/1 20:11
 */
@Configuration
@EnableAsync
public class AsyncConfig {

    /**
     * 注册一个简单线程池
     * @return java.util.concurrent.Executor
     * @author sword
     * @date 2022/3/1 20:13
     */
    @Bean
    public Executor simpleExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 核心线程数
        executor.setCorePoolSize(2);
        // 最大线程数
        executor.setMaxPoolSize(2);
        // 队列大小
        executor.setQueueCapacity(10);
        // 空闲线程存活时间
        executor.setKeepAliveSeconds(60);
        // 线程池中创建的线程的名称前缀，大于15字符则名称可能会被截掉
        executor.setThreadNamePrefix("executor-1-");
        // 如果线程池满了拒绝执行任务，则直接在调用线程中运行被拒绝的任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 在spring容器里注册的线程池不需要我们来执行initialize()进行初始化，如果是其他现建现用的地方就需要执行initialize()进行初始化了
        // executor.initialize();

        return executor;
    }
}
